var toast_time = 3000;
var app_version = '1.0';
var appid = "A6012865121096";
var apikey =  '5a38ab0673384717';
var arr_wel = new Array();
//关闭启动图
function close_start_page(callback) //config.xml中的autoLaunch设置为false;
{
    if (is_define(callback)) {
        callback();
    }
    setTimeout(function() {
        api.removeLaunchView({
            animation: {
                type: 'push',
                duration: 500
            }
        });
    }, 2000);
}
//字符串转json
function str2json(s) {
    var json = eval('(' + s + ')');
    return json;
}
/**
 * [_ajax ajax函数封装]
 * @param  {[type]}   serverURL      [地址]
 * @param  {[type]}   data           [数据]
 * @param  {Function} callback       [回调]
 */
function _ajax(serverURL, data, callback) {
    var param = {
        apikey: apikey
    };
    Object.assign(param, data);
    // show_doing();
    // api.ajax({
    //     url: serverURL,
    //     method: 'post',
    //     headers: {
    //         // 'Content-Type': 'application/json;charset=utf-8'
    //     },
    //     data: {
    //         body: param
    //     }
    // }, function(ret, err) {
    //     hide_doing();
    //     if (callback) {
    //         callback(ret);
    //     }
    // });

    showLoad(function(flowerid) {
        $.ajax({
            type: "POST",
            url: serverURL,
            data: param,
            success: function(result) {
                hideLoad(flowerid);
                if (callback) {
                    callback(result);
                }
            },
            error: function(err) {
                hideLoad(flowerid);
                if (callback) {
                    callback(err);
                }
            }
        });
    });

}

function isLogin() {
    var userInfo = get_local('userInfo');
    if (!userInfo) {
        var name = "login";
        var url = "widget://html/login/login.html";
        openWin(name, url);
        return false;
    } else {
        return true;
    }
}

// 显示加载
function showLoad(callback) {
    var UILoading = api.require('UILoading');
    UILoading.flower({
        center: {},
        size: 30,
        mask: 'rgba(0,0,0,0.1)',
        fixedOn: api.frameName,
        fixed: true
    }, function(ret) {
        if (callback) {
            callback(ret.id);
        }
    });
}

// 关闭加载
function hideLoad(flowerid) {
    setTimeout(function() {
        var uiloading = api.require('UILoading');
        uiloading.closeFlower({
            id: flowerid
        });
    }, 300);
}


/**
 * [res_ajax ajax函数封装]
 * @param  {[type]}   serverURL      [地址]
 * @param  {[type]}   data           [数据]
 * @param  {Function} callback       [回调]
 * @param  {Boolean}  [isToken=true] [是否需要token 默认true]
 * @return {[type]}                  [description]
 */
function res_ajax(serverURL, data, callback, isToken = true) {
    var token = $api.getStorage('token');
    if (!token && isToken === true) {
        set_sendEvent('reLogin');
        return false;
    }
    show_doing();
    api.ajax({
        url: serverURL,
        method: 'post',
        timeout: 30,
        dataType: 'json',
        cache: false,
        headers: {
            'XX-Token': token,
            'XX-Device-Type': 'mobile'
        },
        returnAll: false,
        data: data
    }, function(ret, err) {
        hide_doing();
        if (ret) {
            //如果返回10001则需重新登录
            if (ret.code == 10001) {
                $toast(ret.msg);
                //发送重新登录事件
                set_sendEvent('reLogin');
                return false;
            }
            if (callback) {
                callback(ret);
            }
        } else {
            net_error(); //请求失败
        }
    });
}
/**
 * [open_w 打开新的Win窗口]
 * @param  {[type]} name                 [字符串 Win的name值]
 * @param  {[type]} url                  [字符串 Win的相对路径]
 * @param  {[type]} pageParam            [JSON 对象 （可选项）页面参数，新页面中可以通过 api.pageParam 获取]
 * @param  {[type]} slidBackEnabledState [布尔 默认值：true （可选项）是否支持滑动返回。iOS7.0及以上系统中，在新打开的页面中向右滑动，可以返回到上一个页面，该字段只 iOS 有效]
 */
function open_w(name, url, pageParam, slidBackEnabledState, reload = false) {
    if (is_define(pageParam)) {
        var pageParam = pageParam;
    } else {
        var pageParam = new Object();
    }
    if (is_define(slidBackEnabledState)) {
        var slidBackEnabledState = true;
    } else {
        var slidBackEnabledState = slidBackEnabledState;
    }

    api.openWin({
        name: name,
        url: url,
        delay: 1,
        slidBackEnabled: slidBackEnabledState,
        pageParam: pageParam,
        reload: reload
    });
}
//关闭当前页面
function close_w() {
    api.closeWin();
}
//关闭指定页面
function close_name_w(name) {
    if (api.systemType == 'ios') {
        setTimeout
            (
                function() {
                    api.execScript({
                        name: "root",
                        script: "api.closeWin({name:'" + name + "'});"
                    });
                }, 500
            )
    } else {
        api.closeWin({
            name: name
        });
    }
}
/**
 * [open_f_mask 打开一个遮罩层Frame]
 * @param  {[type]} url       [description]
 * @param  {[type]} pageParam [description]
 * @return {[type]}           [description]
 */
function open_f_mask(url, pageParam) {
    if (is_define(pageParam)) {
        var pageParam = pageParam;
    } else {
        var pageParam = new Object();
    }
    api.openFrame({
        name: 'mask',
        url: url,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: 'auto'
        },
        bounces: true,
        opaque: false,
        pageParam: pageParam,
        allowEdit: true,
        bgColor: 'rgba(0,0,0,0.5)', //主要是这里起作用哦
        vScrollBarEnabled: true,
        hScrollBarEnabled: true,
        reload: false
    });
}
/**
 * [open_f 打开Frame页面]
 * 计算Frame页面的高度
 * @param  {[type]} name         [字符串  Frame的name值]
 * @param  {[type]} url          [字符串 Frame的相对路径]
 * @param  {[type]} pageParam    [JSON 对象 （可选项）页面参数，新页面中可以通过 api.pageParam 获取]
 * @param  {[type]} bouncesState [默认值：true 布尔（可选项）页面是否弹动]
 * @param  {[type]} reload [默认值：false 布尔（可选项）是否重新加载]
 */
function open_f(name, url, pageParam, bouncesState, reload = false) {
    if (is_define(pageParam)) {
        var pageParam = pageParam;
    } else {
        var pageParam = new Object();
    }
    var $header = $api.dom('header');
    $api.fixIos7Bar($header);
    var $body = $api.dom('body');
    var header_h = $api.offset($header).h;
    if (is_define($api.byId('footer'))) {
        var footer_h = $api.offset($api.byId('footer')).h;
        frameheight = api.winHeight - $api.byId('footer').offsetHeight - $api.byId('header').offsetHeight;
    } else {
        frameheight = "auto";
    }

    if (is_define(bounces)) {
        var bounces = true;
    } else {
        var bounces = bouncesState;
    }
    api.openFrame({
        name: name,
        url: url,
        rect: {
            x: 0,
            y: header_h,
            w: 'auto',
            h: frameheight
        },
        bounces: bounces,
        //opaque : true,
        allowEdit: true,
        pageParam: pageParam,
        bgColor: 'rgba(0,0,0,0)',
        vScrollBarEnabled: true,
        hScrollBarEnabled: true,
        reload: reload
    });
}
//打开侧滑
function open_slide() {
    api.openSlidPane({
        type: 'left'
    });
}
//关闭侧滑
function close_slide() {
    api.closeSlidPane();
}

//隐藏frame
function hide_f(name) {
    api.setFrameAttr({
        name: name,
        hidden: true,
    });
}
//关闭frame
function close_f(name) {
    api.closeFrame({
        name: name
    });
}
//得到frame的高度
function get_f_h() {
    return api.frameHeight;
}
/**
 * [$toast 提示框]
 * @param  {[type]} txt      [字符串	提示消息]
 * @param  {[type]} duration [数字	默认值：2000;可选项）持续时长，单位：毫秒]
 * @param  {[type]} location [字符串	默认值：bottom;（可选项）弹出位置，顶部、中间或底部]
 */
function $toast(txt, duration, location) {
    if (!is_define(txt)) {
        txt = 'Loading...';
    }
    if (!is_define(duration)) {
        duration = toast_time;
    }
    if (!is_define(location)) {
        location = 'middle';
    }
    api.toast({
        msg: txt,
        duration: duration,
        location: location
    });
}
//警告框
function $alert(txt, title, button) {
    if (!is_define(title)) {
        var title = "";
    }
    if (!is_define(button)) {
        var button = "确定";
    }
    api.alert({
        title: title,
        msg: txt,
        buttons: [button]
    });
}
//type=date选择日期，type=date_time选择日期时间,type=time选择时间
function open_datetime(type, title, datetime, callback) {
    if (get_os() == "android" && type == "date_time") {
        var true_type = "date";
    } else {
        var true_type = type;
    }
    if (!is_define(title)) {
        var title = "";
    }
    if (!is_define(datetime)) {
        var datetime = "";
    }
    api.openPicker({
        type: true_type,
        date: datetime,
        title: title
    }, function(ret, err) {
        if (type == "date") {
            var back_str = ret.year + "-" + num_two(ret.month) + "-" + num_two(ret.day);
            if (is_define(callback)) {
                callback(back_str);
            }
        } else if (type == "time") {
            var back_str = num_two(ret.hour) + ":" + num_two(ret.minute);
            if (is_define(callback)) {
                callback(back_str);
            }
        } else if (type == "date_time") {
            if (get_os() == "ios") {
                var back_str = ret.year + "-" + num_two(ret.month) + "-" + num_two(ret.day) + " " + num_two(ret.hour) + ":" + num_two(ret.minute);
                if (is_define(callback)) {
                    callback(back_str);
                }
            } else {
                var back_str = ret.year + "-" + num_two(ret.month) + "-" + num_two(ret.day);
                api.openPicker({
                    type: 'time',
                    title: '选择时间'
                }, function(rets, errs) {
                    back_str = back_str + " " + num_two(rets.hour) + ":" + num_two(rets.minute);
                    if (is_define(callback)) {
                        callback(back_str);
                    }
                })
            }
        }
    });
}
//下拉刷新
function push_down(callbak) {
    api.setRefreshHeaderInfo({
        visible: true,
        bgColor: '#f1f1f1',
        textColor: '#4d4d4d',
        textDown: '下拉刷新...',
        textUp: '松开刷新...',
        showTime: true
    }, function(ret, err) {
        if (callbak) {
            callbak();
        }
    });
}

//下拉刷新恢复
function push_down_over() {
    api.refreshHeaderLoadDone();
}
//上拉加载
function push_up(callback) {
    api.addEventListener({
        name: 'scrolltobottom',
        extra: {
            threshold: 0 //设置距离底部多少距离时触发，默认值为0，数字类型
        }
    }, function(ret, err) {
        /*---2017-03-14关闭 官方已经完善加载时的等待机制
        var html='<div id="pushup_trip"><img  src="../../image/loading_more.gif"></div>';
        $("body").append(html);*/
        if (is_define(callback)) {
            callback();
        }
    });
}
//上拉加载恢复---2017-03-14关闭 官方已经完善加载时的等待机制
/*function push_up_over()
{
	$("#pushup_trip").remove();
}*/
//拨打电话
function call_tel(tel) {
    api.call({
        type: 'tel_prompt',
        number: tel
    });
}
//发送短息
function send_sms(tel, text, c1, c2) {
    api.sms({
        numbers: [tel],
        text: text
    }, function(ret, err) {
        if (ret.status) {
            if (is_define(c1)) {
                c1();
            } else {
                $toast('发送成功');
            }
        } else {
            if (is_define(c2)) {
                c2();
            } else {
                $toast('发送失败');
            }
        }
    });
}

//加载网页
function open_url(url) {
    if (get_os() == 'ios') {
        api.openApp({
            iosUrl: url
        }, function(ret, err) {});
    } else {
        api.openApp({
            androidPkg: 'android.intent.action.VIEW',
            mimeType: 'text/html',
            uri: url
        }, function(ret, err) {});
    }
}

//获得设备编号
function get_osid(callback) {
    var deviceId = api.deviceId;
    deviceId = deviceId.replace(/\-/g, "");
    if (is_define(callback)) {
        callback(deviceId);
    } else {
        return deviceId;
    }
}
//显示模态加载
function show_doing(title, text) {
    if (!is_define(title)) {
        var title = '';
    }
    if (!is_define(text)) {
        var text = '';
    }
    api.showProgress({
        style: 'default',
        animationType: 'fade',
        title: title,
        text: text
    });
}
//关闭模态加载
function hide_doing() {
    api.hideProgress();
}
//检测版本更新
function check_update() {
    var mam = api.require('mam');
    mam.checkUpdate(function(ret, err) {
        if (ret) {
            var result = ret.result;
            if (ret.status == 1) {
                if (result.update) {
                    api.confirm({
                            title: '版本更新',
                            msg: '发现新版本：' + result.version + ',' + result.updateTip,
                            buttons: ['确定更新', '稍后再说']
                        },
                        function(ret, err) {
                            if (ret.buttonIndex == 1) {
                                if (api.systemType == 'ios') {
                                    api.installApp({
                                        appUri: result.source //安装包对应plist地址
                                    });
                                    exit_app();
                                } else {
                                    location.href = result.source;
                                }
                            }
                        })
                } else {
                    $toast('暂无新版本', '1000');
                }
            } else {
                $toast('暂无新版本', '1000');
            }
        } else {
            api.alert({
                msg: err.msg
            });
        };
    });
}
//静默更新
function update_widget() {
    api.addEventListener({
            name: 'smartupdatefinish'
        },
        function(ret, err) {
            if (is_define(ret.value[0].extra)) {
                $confirm(ret.value[0].extra, '请重启应用', '', new Array('', exit_app));
            }
        });
}
//退出APP
function exit_app() {
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {
        api.toast({
            msg: '再按一次退出' + api.appName,
            duration: 2000,
            location: 'bottom'
        });
        api.addEventListener({
            name: 'keyback'
        }, function(ret, err) {
            api.closeWidget({
                silent: true
            });
        });
    });
}

//执行指定窗口界面
function ue_script(winname, framename, fun) {
    if (is_define(winname) && is_define(framename)) {
        //在名为winName的window中找到名为frmName的frame，并在该frame中执行fun脚本
        api.execScript({
            name: winname,
            frameName: framename,
            script: fun
        });
    } else if (is_define(winname)) {
        //在名为winName的window中执行fun脚本
        api.execScript({
            name: winname,
            script: fun
        });
    } else if (is_define(framename)) {
        //在当前window中找到名为frmName的frame，并在该frame中执行fun脚本
        api.execScript({
            name: framename,
            script: fun
        });
    } else {
        //在当前window中执行fun脚本
        api.execScript({
            script: fun
        });
    }
}

//清除缓存
function clear_cache(callback) {
    api.clearCache(
        function(ret, err) {
            $toast('已清除', 1000);
            if (is_define(callback)) {
                callback();
            }
        }
    );
}
//网络不好的情况
function net_error(callback) {
    $toast('网络开小差', 1000);
    if (is_define(callback)) {
        callback();
    }
}
/**
 * [select_img 图片选择]
 * @param  {Function} callback     [回调]
 * @param  {String}   [title='']   [描述]
 * @param  {String}   [type='url'] [返回类型]
 * @return {[type]}                [description]
 */
function select_img(callback, title = '', type = 'url') {
    if (!is_define(callback)) {
        var callback = '';
    }
    api.actionSheet({
        title: title,
        cancelTitle: '关闭',
        buttons: ['打开相机', '本地图库']
    }, function(ret, err) {
        if (ret.buttonIndex == 3) {
            return false;
        } else {
            var type_arr = new Array('camera', 'library');
            api.getPicture({
                sourceType: type_arr[ret.buttonIndex - 1],
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: type,
                allowEdit: true,
                quality: 50,
                // targetWidth : 300,
                // targetHeight : 300,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret && is_define(ret.data)) {
                    if (is_define(callback)) {
                        callback(ret);
                    }
                }
            })
        }
    });
}
//获取页面参数
function get_par() {
    return api.pageParam;
}
//下载
function download(url, callback) {
    var file_arr = url.split(".");
    var file_arr_len = file_arr.length;
    var ext_name = file_arr[file_arr_len - 1]; //得到扩展名
    var filename = new Date().getTime() + "." + ext_name;
    var savepath = 'fs://' + filename;
    api.download({
        url: url,
        savePath: savepath,
        report: true,
        cache: true,
        allowResume: true
    }, function(ret, err) {
        if (ret.state == 1) {
            if (is_define(callback)) {
                callback(ret.savePath);
            }
        }
    });
}
//获取系统类型
function get_os(callback) {
    var os = api.systemType;
    if (is_define(callback)) {
        callback(os);
    } else {
        return os;
    }
}
//获取位置
function get_location(callback) {
    api.getLocation(
        function(ret, err) {
            if (ret.status) {
                api.stopLocation();
                if (is_define(callback)) {
                    callback(ret.latitude, ret.longitude);
                }
            } else {
                $toast('定位失败');
            }
        }
    );
}
//获取网络情况
function get_net() {
    //如果unknown-未知，ethernet-以太网，wifi-wifi，2g-2G网络，3g-3G网络，4g-4G网络，none-无网络
    return api.connectionType;
}
//设置本地存储
function set_local(key, val) {
    $api.setStorage(key, val);
    //set_local(key, val);
}
//获取本地存储
function get_local(key) {
    return $api.getStorage(key);
    //return get_local(key);
}
//发送监听
function set_sendEvent(name) {
    api.sendEvent({
        name: name,
    });
}
//接收监听事件
function get_addEventListener(options, callback) {
    api.addEventListener({
        name: options.name,
        extra: options.extra ? options.extra.threshold : 0
    }, function(ret, err) {
        if (true) {
            callback && callback(ret);
        } else {
            callback && callback(err);
        }
    });
}

/**
 * [set_historyBack 历史记录后退一页]
 * @param {[type]} frameName [frame 名称，若不传则表示对当前页面进行操作]
 * @param callback(ret, err) ret.status //后退是否成功，失败时说明不能再后退了
 */
function set_historyBack(frameName) {
    api.historyBack({
        frameName: frameNames
    }, function(ret, err) {
        if (!ret.status) {
            api.closeWin();
        }
    });
}
/**
 * [set_BarStyle 设置状态栏样式为白色（适用于深色背景）或黑色（适用于浅色背景），以及设置状态栏背景颜色和沉浸式设置]
 * @param {[type]} style [dark	状态栏字体为黑色，适用于浅色背景；light	状态栏字体为白色，适用于深色背景]
 * @param {[type]} color [颜色值 字符串 默认值：#000		（可选项）状态栏背景颜色，只 Android 5.0 及以上有效]
 */
function set_BarStyle(style, color) {
    api.setStatusBarStyle({
        style: style,
        color: color
    });
    var header = document.querySelector('header');
    $api.fixIos7Bar(header); /*适配iOS7+系统状态栏，为传入的DOM元素增加20px的上内边距 自动识别iOS7+，避免应用与状态栏重叠，无法跟config.xml里面的 <preference name="iOS7StatusBarAppearance" value="false" /> 一起使用。*/
    $api.fixStatusBar(header); /*适配iOS7+、Android4.4+系统状态栏，为传入的DOM元素增加适当的上内边距，避免header与状态栏重叠，自动识别iOS7+，避免应用与状态栏重叠，无法跟config.xml里面的 <preference name="statusBarAppearance" value="false" /> 一起使用。*/
}
/**
 * [set_doT doT模板封装]
 * @param {[type]}   data_      [从服务器端获取的数据]
 * @param {[type]}   dotID      [dot模板的id名称]
 * @param {[type]}   contentId  [要插入内容的div标签的id]
 * @param {Boolean}  isPullDown [是否为下拉刷新]
 * @param {Function} callback   [description]
 */
function set_doT(data_, dotID, contentId, isPullDown) {
    var apendText = $api.byId(dotID).text;
    var fnapendText = doT.template(apendText);
    var html = fnapendText(data_);
    var list = $api.byId(contentId);
    if (isPullDown) {
        $api.html(list, html);
    } else {
        $api.append(list, html);
    }
    api.parseTapmode(); //之后用代码创建的 dom 元素，则需要调用该方法后 tapmode 属性才会生效
}


/**
 * [nofind 图片加载失败时用默认图]
 * @param  {[type]} defaultImageUrl [字符串 图片相对于要使用页的路径]
 */
function nofind(defaultImageUrl) {
    var img = event.srcElement;
    img.src = defaultImageUrl;
    img.onerror = null;
}

/**
 * [set_imageCache 图片缓存]
 * @param {[type]} obj_ [对象]
 */
function set_imageCache(obj_) {
    var imageURL = $api.attr(obj_, 'data-url'); //获取图片路径
    //当有图片时，替换默认图片
    if (imageURL) {
        api.imageCache({
            url: imageURL
        }, function(ret, err) {
            if (ret.status) {
                obj_.src = ret.url;
                $api.removeAttr(obj_, 'data-url');
            }
        });
    }
}

/*======文件缓存机制======*/
//读文件
function readFile(path, callBack) {
    var cacheDir = api.cacheDir;
    api.readFile({
        path: cacheDir + path
    }, function(ret, err) {
        callBack(ret, err);
    });
}

//写文件
function writeFile(json, id, path) {
    //缓存目录
    var cacheDir = api.cacheDir;
    api.writeFile({
        //保存路径
        path: cacheDir + '/' + path + '/' + id + '.json',
        //保存数据，记得转换格式
        data: JSON.stringify(json)
    }, function(ret, err) {

    })
}
//缓存方法
function doCache(folder, id, url, callback) {
    readFile('/' + folder + '/' + id + '.json', function(ret, err) {
        if (ret.status) {
            //如果成功，说明有本地存储，读取时转换下数据格式
            //拼装json代码
            //alert('取到缓存')
            var cacheData = ret.data;
            callback(JSON.parse(cacheData));
            iCache($('.cache'));
            //再远程取一下数据，防止有更新
            ajaxRequest(url, 'GET', '', function(ret, err) {
                if (ret) {
                    if (cacheData != JSON.stringify(ret)) {
                        //有更新处理返回数据
                        //alert('更新缓存')
                        callback(ret);
                        //缓存数据
                        writeFile(ret, id, folder);
                        iCache($('.cache'));
                    }
                } else {
                    alert('数据获取失败！');
                }
            })
        } else {
            //如果失败则从服务器读取，利用上面的那个ajaxRequest方法从服务器GET数据
            ajaxRequest(url, 'GET', '', function(ret, err) {
                if (ret) {
                    //处理返回数据
                    //alert('没取到缓存')
                    callback(ret);
                    //缓存数据
                    writeFile(ret, id, folder);
                    iCache($('.cache'));
                } else {
                    alert('数据获取失败！');
                }
            })
        }
    })
}

//缓存图片
function iCache(selector) {
    selector.each(function(data) {
        ! function(data) {
            var url = selector.eq(data).attr("src");
            var img = this;
            var pos = url.lastIndexOf("/");
            var filename = url.substring(pos + 1);
            var path = api.cacheDir + "/pic/" + filename;
            var obj = api.require('fs');
            obj.exist({
                path: path
            }, function(ret, err) {
                //msg(ret);
                if (ret.exist) {
                    if (ret.directory) {
                        //api.alert({msg:'该路径指向一个文件夹'});
                    } else {
                        //api.alert({msg:'该路径指向一个文件'});
                        //selector.eq(data).src=path;
                        selector.eq(data).attr('src', null);
                        path = api.cacheDir + "/pic/" + filename;
                        selector.eq(data).attr('src', path);
                        //console.log(selector.eq(data).attr("src"));
                    }
                } else {
                    api.download({
                        url: url,
                        savePath: path,
                        report: false,
                        cache: true,
                        allowResume: true
                    }, function(ret, err) {
                        //msg(ret);
                        if (ret) {
                            var value = ('文件大小：' + ret.fileSize + '；下载进度：' + ret.percent + '；下载状态' + ret.state + '存储路径: ' + ret.savePath);
                        } else {
                            var value = err.msg;
                        };
                    });
                }
            });
        }(data);
    });
};

//点击验证码显示倒计时
/**
 * 不用理会*
 * [CountDown SMS_countdown方法执行时需要的方法]
 */
function CountDown() {
    if (times < 1) {
        var sendVerify = $api.byId('sendVerify');
        $api.attr(sendVerify, 'onclick', 'verificationCode()');
        $api.attr(sendVerify, 'status', '1');
        api.parseTapmode();
        $api.html(sendVerify, '重新获取');
        clearInterval(isinerval);
        return;
    }
    var getVerify = $api.byId('GetVerify');
    $api.html(getVerify, '' + times + '');
    times--;
}
/**
 * [SMS_countdown 发送短信按钮倒计时]
 * @param {[type]}   IdName   [string 按钮的id]
 * @param {[type]}   RunTime  [number 时间长短]
 * @param {Function} callback [description]
 */
function SMS_countdown(IdName, RunTime, callback) {
    var sendVerify = $api.byId(IdName);
    var status = $api.attr(sendVerify, 'status');
    if (status != 1) {
        $toast('短时间内不能重复发送');
        return;
    }
    $api.html(sendVerify, '<span id="GetVerify">' + RunTime + '</span>S');
    times = RunTime;
    isinerval = setInterval("CountDown()", 1000);
    if (is_define(callback)) {
        callback();
    }
    var status = $api.attr(sendVerify, 'status', '2');
}

//发送阿里大鱼短信验证
function verificationCode() {
    var mobile = $api.val($api.byId('mobile')); //用户手机号
    if (!is_define(mobile)) {
        $toast('手机号不能为空');
        return;
    }
    /*判断是否已经注册过*/
    var is_registeredURL = Config.api.User_Registered,
        data = {
            values: {
                mobile: mobile
            }
        };
    r_ajax(is_registeredURL, data, function(ret) {
        if (ret.data.status == '1') {
            /*点击验证码显示倒计时*/
            SMS_countdown('sendVerify', '120', function() {
                /*发送短信*/
                var send_smsURL = Config.api.Send_Sms,
                    sdata = {
                        values: {
                            mobile: mobile
                        }
                    };
                r_ajax(send_smsURL, sdata, function(sret) {
                    if (sret.data.status == 1) {
                        $toast(sret.data.msg);
                    } else {
                        $toast(sret.data.msg);
                    }
                });
            });
        } else {
            $toast(ret.data.msg);
        }
    })
}


//显示模态加载
function showProgress() {
    api.showProgress({
        animationType: 'zoom',
        title: '努力加载中...',
        text: '先喝杯茶...',
        modal: true
    });
}

/**
 * 判断是否是空
 * @param value
 */
function is_define(value) {
    if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof(value) == 'undefined') {
        return false;
    } else {
        value = value + "";
        value = value.replace(/\s/g, "");
        if (value == "") {
            return false;
        }
        return true;
    }
}
//是否是json对象
function is_json(obj) {
    var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
    return isjson;
}



/**
 * [LoadImage 图片开启缓存]
 * @param {[obj]} ele_ [当前元素]
 */
function LoadImage(ele_) {
    var imageURL = $api.attr(ele_, 'data-url');
    if (imageURL) {
        api.imageCache({
            url: imageURL
        }, function(ret, err) {
            if (ret.status) {
                ele_.src = ret.url;
                $api.removeAttr(ele_, 'data-url');
            }
        });
    }
}

/**
 * [openWin 打开新窗口]
 * @param  {[string]} name      [win名称]
 * @param  {[string]} url       [页面地址]
 * @param  {[object]} pageParam [对象参数组]
 */
function openWin(name, url, pageParam) {
    if (isDefine(pageParam)) {
        var pageParam = pageParam;
    } else {
        pageParam = new Object();
    }
    api.openWin({
        name: name,
        url: url,
        pageParam: pageParam
    });
}

/**
 * [openFrame 打开frame]
 * @param  {[string]}    name        [frame名称]
 * @param  {[string]}     url         [页面地址]
 * @param  {[object]}     pageParam   [对象参数组]
 * @param  {[string]}     isBounces   [是否弹动]
 * @link http://www.kancloud.cn/hongweizhiyuan/apicloud_function/270222
 */
function openFrame(name, url, pageParam, isBounces = false) {
    if (isDefine(pageParam)) {
        var pageParam = pageParam;
    } else {
        pageParam = new Object();
    }
    var header = document.querySelector('header');
    $api.fixStatusBar(header);
    var headerPos = $api.offset(header);
    api.openFrame({
        name: name,
        url: url,
        pageParam: pageParam,
        bounces: isBounces,
        slidBackEnabled: 'false',
        rect: {
            x: 0,
            y: headerPos.h,
            w: 'auto',
            h: 'auto'
        }
    })
}

/**
 * [isDefine 判断值是否定义]
 * @param  {[string]}  value
 * @return {Boolean}
 */
function isDefine(value) {
    if (value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof(value) == 'undefined') {
        return false;
    } else {
        value = value + "";
        value = value.replace(/\s/g, ""); //全局匹配空白字符
        if (value == "") {
            return false;
        }
        return true;
    }
}

/**
 * [dotTpl doT模板获取数据]
 * @ hongwei
 * @param  {[type]} dotId  [相应数据的doT模板ID-必须]
 * @param  {[type]} htmlID [相应html的ID-必须]
 * @param  {[type]} data_  [ajax获取]
 * @return {[type]}        [description]
 * @link http://www.kancloud.cn/hongweizhiyuan/apicloud_function/274615
 */
function dotTpl(dotId, htmlID, data_) {
    var apendText = $api.byId(dotId).text;
    var fnapendText = doT.template(apendText);
    var html = fnapendText(data_);
    var list = $api.byId(htmlID);
    $api.html(list, html);
}


/**
 * [提示在开发中]
 * @author Hongwei
 * @link http://www.kancloud.cn/hongweizhiyuan/apicloud_function/270054
 */
function developing(msg) {
    api.toast({
        msg: msg,
        duration: 2000,
        location: 'middle'
    });
}

/**
 * [showToast 显示模态提示]
 * @param  {[string]} msg      [消息内容]
 * @param  {[string]} duration [模态框显示时间]
 * @param  {[string]} location [模态框显示位置,top/middle/bottom]
 */
function showToast(msg, duration, location) {
    var msg = msg ? msg : '错误';
    var duration = duration ? duration : '2000';
    var location = location ? location : 'bootom';
    api.toast({
        msg: msg,
        duration: duration,
        location: location
    });
}


//获取缓存
function fnGetCacheSize() {
    api.getCacheSize(function(ret) {
        if (ret) {
            var size = parseInt(ret.size / 1024 / 1024 * 100) / 100 + ' MB';
            var cacheSize = $api.byId('cacheSize');
            cacheSize.innerHTML = size;
        } else {
            var cacheSize = $api.byId('cacheSize');
            cacheSize.innerHTML = '0MB';
        }
    });
}
//清除缓存
function fnClearCache() {
    api.showProgress({
        title: '清除缓存中...',
    });
    api.clearCache(function() {
        setTimeout(function() {
            api.hideProgress();
            fnGetCacheSize();
        }, 500)
    });
}
//js实现数组转换成json
function arrayToJson(o) {
    var r = [];
    if (typeof o == "string") return "\"" + o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "object") {
        if (!o.sort) {
            for (var i in o)
                r.push(i + ":" + arrayToJson(o[i]));
            if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
                r.push("toString:" + o.toString.toString());
            }
            r = "{" + r.join() + "}";
        } else {
            for (var i = 0; i < o.length; i++) {
                r.push(arrayToJson(o[i]));
            }
            r = "[" + r.join() + "]";
        }
        return r;
    }
    return o.toString();
}


/**
 * [timestampToTime 时间锉转换]
 * @param  {[type]} timestamp [时间锉]
 * @return {[type]}           [时间]
 */
function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y + M + D + h + m + s;
}

function timestampToTime_YMDhm(timestamp) {
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes();
    return Y + M + D + h + m;
}
/**
 * [getBase64Image 图片转换base64]
 * @param  {[type]} img [图片路劲]
 * @return {[type]}     [base64字符串]
 */
function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, img.width, img.height);
    var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
    var dataURL = canvas.toDataURL("image/" + ext);
    return dataURL;
}

function replaceHtml(cont) {
    cont = cont.replace(/(\n)/g, "");
    cont = cont.replace(/(\t)/g, "");
    cont = cont.replace(/(\r)/g, "");
    cont = cont.replace(/<\/?[^>]*>/g, "");
    cont = cont.replace(/\s*/g, "");
    return cont;
}

/**
 * [wxShareUrl 微信分享网页（shareWebpage）]
 * @param  {[type]} contentUrl              [分享链接]
 * @param  {String} [title='标题']            [标题]
 * @param  {String} [description='分享内容的描述'] [描述]
 * @param  {String} [thumb='']              [分享网页的缩略图地址，要求本地路径（fs://、widget://）大小不能超过32K,需要路径包含图片格式后缀，否则如果原图片为非png格式，会分享失败]
 * @return {[type]}                         [description]
 */
function wxShareUrl(contentUrl, title = '标题', description = '分享内容的描述', thumb = '', callback) {
    api.actionSheet({
        title: '微信分享',
        cancelTitle: '关闭',
        buttons: ['好友', '朋友圈', '收藏']
    }, (ret, err) => {
        if (ret) {
            var arr = ['session', 'timeline', 'favorite'];
            let scene = arr[ret.buttonIndex - 1];
            if (scene) {
                var wx = api.require('wx');
                wx.isInstalled((ret, err) => {
                    if (ret.installed) {
                        wx.shareWebpage({
                            apiKey: '',
                            scene: scene,
                            title: title,
                            description: description,
                            thumb: thumb,
                            contentUrl: contentUrl
                        }, (ret, err) => {
                            if (ret.status) {
                                $toast('分享成功');
                            } else {
                                switch (err.code) {
                                    case 0:
                                        break;
                                    case 2:
                                        $toast('您取消了操作!');
                                        break;
                                    default:
                                        $toast('系统错误,请稍后重试或者联系管理员!');
                                }
                            }
                            if (callback) {
                                callback(ret, err);
                            }
                        });
                    } else {
                        $toast('当前设备未安装微信客户端,无法进行分享~');
                    }
                });
            }
        }
    })
}

/**
 * 图片上传
 * @param  apiUrl 接口地址
 * @param  e 插入图片的dom对象
 */
function imageUpload(apiUrl, callback) {
    api.actionSheet({
        title: '上传头像',
        cancelTitle: '关闭',
        buttons: ['图片库', '相机 ', '相册']
    }, function(ret, err) {
        var index = ret.buttonIndex;
        var type = new Array('library ', 'camera', 'album');
        if (index != 4) {
            api.getPicture({
                sourceType: type[index - 1],
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'url',
                allowEdit: true,
                quality: 50,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                    var userInfo = get_local('userInfo');

                    showLoad(function(flowerid) {
                        api.ajax({
                            url: apiUrl,
                            method: 'post',
                            data: {
                                values: {
                                    apikey: apikey,
                                    user_id: userInfo.user_id
                                },
                                files: {
                                    imgs: ret.data
                                }
                            }
                        }, function(ret, err) {
                            hideLoad(flowerid);
                            if (is_define(callback)) {
                                callback(ret);
                            }
                        });
                    });


                }
            });
        }
    });
}
